package com.hctforgreen.greenservice;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hctforgreen.greenservice.ParentActivity;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookListEntity;
import com.hctforgreen.greenservice.model.ExamPaperEntity;
import com.hctforgreen.greenservice.utils.CheckDataVersionCodeUtil;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**2016-9-20 
 * 终端培训
 * 考试信息展示页面
 * 
 * @author 390694
 * 
 */
public class TerminalPaperActivity extends ParentActivity {
	private List<ExamPaperEntity.BookClass> bookList;
	private List<BookListEntity.BookEntity> finalBookList;
	private DbController dbController;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.paper_activity);
		initSkinLayout();
		initFinshExamineActivityReceiver();
		initTitleButtonBar();

		updateBaseDataTips();

		Intent intent = getIntent();
		ExamPaperEntity paperEntity = (ExamPaperEntity) intent
				.getSerializableExtra(HctConstants.ON_ACTIVITY_KEY_PAPER_ENTITY);
		dbController = new DbController(this);
		if (paperEntity != null) {
			initWindow(paperEntity);
			initStartBtn(paperEntity);
		} else {
			//从学习资料页面跳转过来的
			final String paperId = getIntent().getStringExtra(
					HctConstants.ON_ACTIVITY_KEY_PAPER_ID);
			initPaperById(paperId);
		}
	}

	/**
	 * 2016-11-5 390694  检查基础数据包版本，提示区更新
	 */
	public void updateBaseDataTips() {
		CheckDataVersionCodeUtil checkDataVersionCodeUtil = new CheckDataVersionCodeUtil();

		checkDataVersionCodeUtil.new CheckDataVersionCodeTask(
				R.string.update_now3,R.string.terminal_update_data_title, TerminalPaperActivity.this, true,
				null, null, null, null, null)
				.execute(TerminalPaperActivity.this);
	}

	/**
	 * 通过试卷id后去试卷详情
	 */
	private void initPaperById(final String paperId) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					HctResult result = (HctResult) msg.obj;
					if (result.data != null) {
						final ExamPaperEntity entity = (ExamPaperEntity) result.data;
						initWindow(entity);
						initStartBtn(entity);
					} else {
						Toast.makeText(TerminalPaperActivity.this,
								getString(R.string.empty), Toast.LENGTH_LONG)
								.show();
					}

					break;
				case HctConstants.STATUS_FAILD:
					Toast.makeText(TerminalPaperActivity.this,
							getString(R.string.net_error_hint),
							Toast.LENGTH_LONG).show();
					break;
				}
				super.handleMessage(msg);
			}
		};
		new HandlerThread("getPapperById") {
			public void run() {
				Message message = handler.obtainMessage();
				HctController controller = new HctController(TerminalPaperActivity.this);
				try {
					HctResult hctResult = controller.getTerminalExamPageByID(paperId);
					message.what = HctConstants.STATUS_SUCCESS;
					message.obj = hctResult;
				} catch (Exception e) {
					message.what = HctConstants.STATUS_FAILD;
					e.printStackTrace();
				}
				handler.sendMessage(message);
			};
		}.start();

	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.train_examine));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	private void initWindow(final ExamPaperEntity paperEntity) {
		final TextView titleTv = (TextView) findViewById(R.id.paper_title);
		final TextView introTv = (TextView) findViewById(R.id.paper_intro);// 简介||备注
		final TextView timesTv = (TextView) findViewById(R.id.tv_time);// 发布时间
		final TextView totalPointTv = (TextView) findViewById(R.id.tv_score);// 总分
		final TextView passScore = (TextView) findViewById(R.id.tv_qualified_score);// 及格分

		if (paperEntity != null ) {
			titleTv.setText(paperEntity.name);
			introTv.setText(paperEntity.remark);
			timesTv.setText(paperEntity.createTime);
			totalPointTv.setText(paperEntity.score + "");
			passScore.setText(paperEntity.passScore + "");

			/**
			 * 2016-1-11 390694 增加判断更新资料的服务是否在进行，是  则提示
			 */
			boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(TerminalPaperActivity.this);
			if (isServiceRunning) {
				Dialog dialog = null;
				AlertDialog.Builder builder = new AlertDialog.Builder(TerminalPaperActivity.this);
				builder.setTitle(R.string.dialog_default_title_hint)
						.setMessage(R.string.update_now2)
						.setPositiveButton(R.string.dialog_confirm_hint,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
														int which) {
										dialog.dismiss();
									}
								});
				dialog = builder.create();
				dialog.show();
				return;
			}else{
				if (paperEntity.bookList != null && (paperEntity.bookList.size() > 0)) {
					bookList = paperEntity.bookList;
					finalBookList = new ArrayList<BookListEntity.BookEntity>();
					//在此处将有用的数据筛选出来，从服务器查询到的书要判断是否在数据库中存在 存在则为有效数据
					for (ExamPaperEntity.BookClass bookClass : bookList) {
						BookListEntity.BookEntity bookEntit = dbController.getBookEntity(bookClass.getBookId());
						if (dbController.isExists(bookEntit)) {
							finalBookList.add(bookEntit);
						}
					}
				}
				//考试关联的资料
				final TextView tipTv = (TextView) findViewById(R.id.tips_tv);
				tipTv.setVisibility(View.VISIBLE);
				final ListView relatedBooksLv = (ListView) findViewById(R.id.relate_materials_lv);
				//有资料
				if (finalBookList!=null && (finalBookList.size() > 0)) {
					tipTv.setVisibility(View.VISIBLE);
					RelatedBooksAdapter adapater = new RelatedBooksAdapter(this, finalBookList);
					relatedBooksLv.setAdapter(adapater);
				}else{
					tipTv.setVisibility(View.GONE);
				}
			}
		}
	}

	private void initStartBtn(final ExamPaperEntity paperEntity) {
		Button startBtn = (Button) findViewById(R.id.btn_start);
		startBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(TerminalPaperActivity.this,
						TerminalCountDownExamDetailActivity.class);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_PAPER_ENTITY,
						paperEntity);
				startActivity(intent);
			}
		});
	}


	class RelatedBooksAdapter extends BaseAdapter {
		private Context context;
		private List list;

		public RelatedBooksAdapter(Context context,List list){
			super();
			this.context = context;
			dbController = new DbController(context);
			this.list = list;

		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final BookListEntity.BookEntity bookEntity = finalBookList.get(position);
				ViewHolder viewHolder = null;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(R.layout.item_related_book_item, null);
					viewHolder = new ViewHolder();
					viewHolder.layout = (LinearLayout) convertView.findViewById(R.id.related_book_item);
					viewHolder.titleTv = (TextView) convertView.findViewById(R.id.related_book_name);

					convertView.setTag(viewHolder);
				} else {
					viewHolder = (ViewHolder) convertView.getTag();
				}

					//从数据库查询bookname对应的那本书
					viewHolder.titleTv.setText(bookEntity.displayName);
					viewHolder.layout.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {

							/**
							 * 2016-12-31 390694 增加判断更新资料的服务是否在进行，是  则提示
							 */
							boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(TerminalPaperActivity.this);
							if (isServiceRunning) {
								Dialog dialog = null;
								AlertDialog.Builder builder = new AlertDialog.Builder(TerminalPaperActivity.this);
								builder.setTitle(R.string.dialog_default_title_hint)
										.setMessage(R.string.update_now)
										.setPositiveButton(R.string.dialog_confirm_hint,
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(DialogInterface dialog,
																		int which) {
														dialog.dismiss();
													}
												});
								dialog = builder.create();
								dialog.show();
								return;
							}
							EntryCatalogUtil util = new EntryCatalogUtil();
							try {
								util.startEntryCatalogActivity((Activity) context, bookEntity, true);
							} catch (Exception e) {
								e.printStackTrace();
							}

						}
					});

				return convertView;

		}


		class ViewHolder{
			public TextView titleTv;
			public LinearLayout layout;
		}
	}
}
